from rest_framework.authentication import BaseAuthentication
from rest_framework import exceptions
from api import models

# class GeneralAuthentication(BaseAuthentication):
#
#     def authenticate(self, request):
#         #1 用户没有携带token
#         token=request.META.get('HTTP_AUTHORIZATION',None)
#
#         if not token:
#             return None
#         #2 用户携带的token不正确
#         user_obj=models.UserInfo.objects.filter(token=token).first()
#         if not user_obj:
#             return None
#         #3 认证成功  (request.user,request.auth)
#         return user_obj,token
#
# class UserAuthentication(BaseAuthentication):
#     '''
#     用户认证 必须登录
#     '''
#     def authenticate(self, request):
#         token=request.META.get('HTTP_AUTHORIZATION',None)
#         if not token:
#             raise exceptions.AuthenticationFailed()
#         user_obj=models.UserInfo.objects.filter(token=token).first()
#         if not user_obj:
#             raise exceptions.AuthenticationFailed()
#         return (user_obj, token) #request.user/request.auth

class GeneralAuthorization(BaseAuthentication):

    def authenticate(self, request):
        token=request.META.get('HTTP_AUTHORIZATION',None)
        if not token:
            return None
        user_obj=models.UserInfo.objects.filter(token=token).first()
        if not user_obj:
            return None
        else:
            return (user_obj,token)


class UserAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token=request.META.get('HTTP_AUTHORIZATION')
        if not token:
            raise exceptions.NotAuthenticated('没有携带token')
        user_obj=models.UserInfo.objects.filter(token=token).first()
        if not user_obj:
            raise exceptions.AuthenticationFailed('token不正确')
        else:
            return (user_obj,token)